<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            思路：组合、排列、子序列问题都需要回溯
            重点：元素可以重复利用

            */
            var combinationSum = function (candidates, target) {
                let result = []
                function backTracking(path, start, sum) {
                    if (sum > target) return
                    if (sum == target) {
                        return result.push([...path])
                    }
                    for (let i = start; i < candidates.length; i++) {
                        path.push(candidates[i])
                        /* 注意：sum+candidates[i]必须放在每次回溯，如果放在path.push后面，那么回溯结束必须把sum-回去 */
                        backTracking(path, i, sum + candidates[i])
                        path.pop()

                        /* 写法二
             path.push(candidates[i])
            sum+=candidates[i]
            backTracking(path,sum, i)
            sum-=candidates[i]
            path.pop()
                        */
                    }
                }
                backTracking([], 0, 0)
                return result
            }
            combinationSum([2, 3, 6, 7], 7)
        </script>
    </body>
</html>
